//
//  CategoryViewController.m
//  HuiPinZhiJia
//
//  Created by MS on 16/8/29.
//  Copyright © 2016年 MS. All rights reserved.
//

#import "CategoryViewController.h"
#import "SuperNav.h"
#import "DataDidplay.h"
@interface CategoryViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSArray *dataSource;//一级列表
@property (assign,nonatomic) BOOL isOpen;//二级列表是否打开
@property (nonatomic,strong) NSIndexPath *selectIndex;
@property (nonatomic,strong) NSArray *itemsArray;//子菜单
@property (nonatomic,strong) UIBarButtonItem *searchBtn;
@end

@implementation CategoryViewController

- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = NO;
}

#pragma mark 创建UITableView
- (void)createTableView
{
    _itemsArray = [NSArray arrayWithObjects:@"魅族",@"苹果",nil];
    _dataSource = [NSArray arrayWithObjects:@"手机",@"服饰",@"化妆品",@"数码",@"电脑",@"零食",@"母婴",@"医药保健",@"生鲜水果",@"机械",@"日用品",@"皮包",@"箱包",@"衣服",@"女士包",nil];
   
    _tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    
    self.tableView.sectionFooterHeight = 0;
    self.tableView.sectionHeaderHeight = 0;
    self.isOpen = NO;
    
    [self.view addSubview:_tableView];
}
#pragma tableView 代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _dataSource.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.isOpen)
    {
        if (self.selectIndex.section == section)
        {
            if (section == 0)
            {
                return 3;
            }
            else if (section == 4)
            {
                return 2;
            }
            else if (section == 13)
            {
                return 2;
            }
            return [_itemsArray count] + 1;
        }
    }
    
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isOpen&&self.selectIndex.section == indexPath.section &&indexPath.row != 0){
        static NSString *cellID = @"CellTwo";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (!cell)
        {
            cell = [[UITableViewCell alloc]init];
        }
        cell.backgroundColor = [UIColor lightGrayColor];
        if (indexPath.section == 0)
        {
            if (indexPath.row == 1)
            {
                cell.textLabel.text = @"魅族";
            }else
            {
            cell.textLabel.text = @"苹果";
            }
        }else if (indexPath.section == 4)
        {
           cell.textLabel.text = @"联想";
            
        }else if (indexPath.section == 13)
        {
        cell.textLabel.text = @"裤子";
        }
        return cell;
    }else
    {
        static NSString *cellId = @"cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (!cell)
        {
            cell = [[UITableViewCell alloc]init];
        }
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

        UILabel *label = [[UILabel alloc]init];
        label.text = _dataSource[indexPath.section];
        label.frame = CGRectMake(100, 1, 150, 50);
        label.font = [UIFont systemFontOfSize:20];
        [cell addSubview:label];
        
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(5, 5, 80, 80)];
        imageView.image = [UIImage imageNamed:@"placeHolder.jpg"];
        [cell addSubview:imageView];
        
        if (indexPath.section == 0)
        {
            UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(100, 35, 180, 40)];
            label1.text = @"魅族 / 苹果";
            [cell addSubview:label1];
        }else if (indexPath.section == 4)
        {
            UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectMake(100, 35, 180, 40)];
            label2.text = @"联想";
            [cell addSubview:label2];

        }else if (indexPath.section == 13)
        {
            UILabel *label3 = [[UILabel alloc]initWithFrame:CGRectMake(100, 35, 180, 40)];
            label3.text = @"裤子";
            [cell addSubview:label3];
        }
        return cell;
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 || indexPath.section == 4 || indexPath.section == 13)
    {
    if (indexPath.row == 0)
    {
        if ([indexPath isEqual:self.selectIndex])
        {
            self.isOpen = NO;
            //关闭
            [self openOrClosedFirst:NO next:NO];
            self.selectIndex = nil;
        }
        else{//打开
            if (!self.selectIndex) {//没有其它的打开
                self.selectIndex = indexPath;
                self.isOpen = YES;
                [self openOrClosedFirst:YES next:NO];
            }
            else{
                self.isOpen = NO;
                [self openOrClosedFirst:NO next:YES];//关闭之前的，打开现在选择的
            }
        }
        
    }
    else{
//        NSLog(@"选中数字");
        DataDidplay *data = [[DataDidplay alloc]init];
        UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:data];
        [self.navigationController pushViewController:data animated:YES];
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];//取消选中
        }
}

/**
 *  打开关闭内容
 *
 *  @param firstState 若为NO代表关闭之前打开的，为YES则打开选择的
 *  @param nextState  若为YES，则需要关闭之前打开的
 */
- (void)openOrClosedFirst:(BOOL)firstState next:(BOOL)nextState
{
    [self.tableView beginUpdates];
    
    long int contentCount;

    
    long int section = self.selectIndex.section;
    
    if (self.selectIndex.section == 0)
    {
        contentCount = 2;
    }else if(self.selectIndex.section == 4 || self.selectIndex.section == 13)
    {
        contentCount = 1;
    }

    NSMutableArray *rowToInsert = [[NSMutableArray alloc]init];
    for (int i = 1; i < contentCount + 1; i ++)
    {
        NSIndexPath *indexPathToInsert = [NSIndexPath indexPathForRow:i inSection:section];
        [rowToInsert addObject:indexPathToInsert];
    }
    
    if (firstState) {
        [self.tableView insertRowsAtIndexPaths:rowToInsert withRowAnimation:UITableViewRowAnimationTop];
    }
    else{
        [self.tableView deleteRowsAtIndexPaths:rowToInsert withRowAnimation:UITableViewRowAnimationTop];
    }
    
    [self.tableView endUpdates];
    
    if (nextState) {
        self.isOpen = YES;
        self.selectIndex = [self.tableView indexPathForSelectedRow];
        [self openOrClosedFirst:YES next:NO];
    }
    
    if (self.isOpen) {
        [self.tableView scrollToNearestSelectedRowAtScrollPosition:UITableViewScrollPositionTop animated:YES];
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isOpen)
    {
        if (self.selectIndex.section == indexPath.section && indexPath.row != 0)
        {
            return 60.f;
        }
    }
        return 100.f;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"所有分类";
    
    [self.navigationController.navigationBar setBarTintColor:[UIColor colorWithRed:0.41 green:0.79 blue:1.00 alpha:1.00]];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor],UITextAttributeFont : [UIFont boldSystemFontOfSize:18]}];
    
    [self createTableView];
    
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(screenWidth - 80, 3, 40, 40);
    [btn setBackgroundImage:[UIImage imageNamed:@"fangdajing"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(searchBar:) forControlEvents:UIControlEventTouchUpInside];
    _searchBtn = [[UIBarButtonItem alloc]initWithCustomView:btn];
    [_searchBtn setTintColor:[UIColor whiteColor]];
   
    self.navigationItem.rightBarButtonItem = _searchBtn;
    // Do any additional setup after loading the view.
}

- (void)searchBar:(id)sender
{
    self.tabBarController.selectedIndex = 2;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
